<template>
    <div class="video-body-container">
        <div class="video-detect-container">
            <div class="video-canvas-container">
                <canvas width="670" height="524" class="image-canvas" ref="videoCanvas"></canvas>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import {defineComponent, ref, onMounted, inject} from 'vue';

export default defineComponent({
    setup() {
        const videoCanvas = ref<any>(null);  // 放置待检测图片的画布元素
        const faceDetectCanvas: any = inject('$faceDetectCanvas');
 
        /**
         * 读取摄像头的视频流，利用定时器检测视频帧后显示在画布中
         */
        function initCanvasVideo() {
            const video: HTMLVideoElement = document.createElement('video');
            const ctx: CanvasRenderingContext2D = videoCanvas.value.getContext('2d') as CanvasRenderingContext2D;
            const videoPromise: Promise<MediaStream> = navigator.mediaDevices.getUserMedia({video: {width: 670, height: 524}});
            let dataUrl: string;  // 视频帧转图片后的URL
            let timer: number;
            
            videoPromise.then(
                (mediaStream) => {
                    if(!timer) {
                        video.srcObject = mediaStream;
                        video.onloadedmetadata = function() {
                            video.play();
                        };
                    }
                    if (timer) {
                        clearInterval(timer);
                    }
                    
                    timer = setInterval(() => {
                        ctx.drawImage(video, 0, 0, 670, 524);
                        dataUrl = videoCanvas.value.toDataURL("image/png");
                        // 检测视频帧，由于性能太低，实时检测设备会崩掉，所以注释掉了
                        // faceDetectCanvas.startDetectImage(videoCanvas.value, dataUrl);
                    }, 15);
            }).catch(() => {
                alert("失败");
            })
        }
        
        onMounted(() => {
            initCanvasVideo();
        })
        
        return {
            videoCanvas,
        };
    },
});
</script>
<style>
.video-body-container {
    height: 100%;
    width: 100%;
    background-color: #fff;
    
    display: flex;
    align-items: center;
    justify-content: center;
}

.video-body-container .video-detect-container {
    height: 5.24rem;
    width: 6.72rem;
    /*background-color: #343434;*/
    
    display: flex;
    flex-direction: column;
}

.video-detect-container .video-canvas-container .image-canvas {
    width: 100%;
    height: auto;
    border: 1px solid #f2180d;
}
</style>